//
//  IndexViewController.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/1/26.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "IndexViewController.h"
#import "HomeListViewController.h"
#import "CYOrderViewController.h"//排行榜
#import "OrderIndexViewController.h"
#import "SELUpdateAlert.h"
#import "Version.h"
#import "OnlineLogicViewController.h"
#import "NSString+Common.h"
#import <UMCPush/UMPush/UMessage.h>
#import "UITabBar+CustomBadge.h"

#import <Photos/Photos.h>
#import "WLAuthorizatView.h"
#import "AuthorizatModel.h"
#import "HomeListSearchViewController.h"

@interface IndexViewController ()<QMUITextFieldDelegate>
{
    NSArray *list;
    QMUIDialogTextFieldViewController *dialogViewController;
}

@property (nonatomic, strong) MLMSegmentHead *segHead;
@property (nonatomic, strong) MLMSegmentScroll *segScroll;

@end

@implementation IndexViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self segmentStyle1];
    self.isShowLiftBack = NO;//每个根视图需要设置该属性为NO，否则会出现导航栏异常
    //多加载几次
    [[UserManager sharedUserManager] loadUserInfo];
    //延迟3秒防止跟广告冲突
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self checkCode];
        
        NSInteger unRead = [IMAPlatform sharedInstance].conversationMgr.unReadMessageCount;
        if(unRead == 0)
        {
            [self.tabBarController.tabBar setBadgeStyle:kCustomBadgeStyleNone value:unRead atIndex:2];
            
        }
        else
        {
            [self.tabBarController.tabBar setBadgeStyle:kCustomBadgeStyleNumber value:unRead atIndex:2];
        }
        
        
        /** App判断第一次启动的方法 */
        NSString *key = @"isFirstCYa";
        
        BOOL isFirst = [[NSUserDefaults standardUserDefaults] boolForKey:key];
        
        if (!isFirst) {
            
            [[NSUserDefaults standardUserDefaults] setBool:@1 forKey:key];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            //权限检测
            AuthorizatModel *mo1 = [[AuthorizatModel alloc]initWithTitle:ASLocalizedString(@"开启地理位置")subTitle:ASLocalizedString(@"给您推荐附近的人")image:ASLocalizedString(@"定位")type:AuthorizatTypeLocation];
            AuthorizatModel *mo2 = [[AuthorizatModel alloc]initWithTitle:ASLocalizedString(@"开启消息通知")subTitle:ASLocalizedString(@"给您推送消息")image:ASLocalizedString(@"通知")type:AuthorizatTypeNotication];
            AuthorizatModel *mo3 = [[AuthorizatModel alloc]initWithTitle:ASLocalizedString(@"开启照相机")subTitle:ASLocalizedString(@"上传照片使用")image:ASLocalizedString(@"照片")type:AuthorizatTypeCamera];
            AuthorizatModel *mo4 = [[AuthorizatModel alloc]initWithTitle:ASLocalizedString(@"开启麦克风")subTitle:ASLocalizedString(@"发送视频聊和语音消息")image:ASLocalizedString(@"语音")type:AuthorizatTypeAudio]; //语音 模拟器不可用
            
            
            NSArray *ary = @[mo1,mo2,mo3,mo4];
            
            WLAuthorizatView *v = [[WLAuthorizatView alloc]init];
            v.data = ary;
            [v show];
            
        } else {
            
            NSLog(ASLocalizedString(@"不是第一次登录"));
        }
        

        
    });
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getConfigSuccess)
                                                 name:KinitConfigLoginSuccess
                                               object:nil];
  
}

- (void)getConfigSuccess {
    
    //审核模式不弹出
    if([KGlobalVariable.appmodel.ios_version intValue] > Version && KGlobalVariable.appmodel.is_ios_base == 1)
    {
        [SELUpdateAlert showUpdateAlertWithVersion:NSStringFormat(@"%@",KGlobalVariable.appmodel.ios_version) Descriptions:@[NSStringFormat(@"%@",KGlobalVariable.appmodel.ios_app_update_des)]];
    }
    
    //公告
    
    YYCache *yyCache=[[YYCache alloc] initWithName:KUserSystemMessage];

    NSString *cacheStr = (NSString *)[yyCache objectForKey:SafeStr([KGlobalVariable.appmodel.system_message md5String])];
    if(cacheStr == nil)
    {
        NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
        NSString *newVersion = KGlobalVariable.appmodel.ios_version;
        if ([currentVersion isEqualToString:newVersion]) {
            QMUIAlertController *alert = [QMUIAlertController alertControllerWithTitle:ASLocalizedString(@"系统公告")message:NSStringFormat(@"%@",KGlobalVariable.appmodel.system_message) preferredStyle:QMUIAlertControllerStyleAlert];
            
            [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"好")style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
                
            }]];
            
            [alert addAction:[QMUIAlertAction actionWithTitle:ASLocalizedString(@"不再提示")style:QMUIAlertActionStyleDefault handler:^(QMUIAlertAction *action) {
                
                [yyCache setObject:SafeStr(KGlobalVariable.appmodel.system_message) forKey:[SafeStr(KGlobalVariable.appmodel.system_message) md5String]];
                
            }]];
            
            [alert showWithAnimated:YES];
        }
    }
    
    //多加载几次
    [[UserManager sharedUserManager] loadUserInfo];
//    
//    [UMessage setAlias:curUser.id  type:@"buguniao" response:^(id  _Nullable responseObject, NSError * _Nullable error) {
//        NSLog(ASLocalizedString(@"绑定别名%@===%@"),responseObject,error);
//        
//    }];

    

}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)checkCode
{
    kWeakSelf(self);
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"invite_api" A:@"is_full_invite_code"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    NSLog(@"=================ID %@",curUser.id);
    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        int is_full = [[responseObject valueForKey:@"is_full"] intValue];
        if(is_full == 0)
        {
            dialogViewController = [[QMUIDialogTextFieldViewController alloc] init];
            dialogViewController.title = ASLocalizedString(@"邀请码");
            
            dialogViewController.textField.placeholder = ASLocalizedString(@"请输入你的邀请码");
            
            [dialogViewController addCancelButtonWithText:ASLocalizedString(@"没有邀请码")block:^(QMUIDialogViewController *dialogViewController) {
                [weakself doSendWithType:@"0"];
            }];
            
            dialogViewController.buttonBackgroundColor = [UIColor whiteColor];
            [dialogViewController addSubmitButtonWithText:ASLocalizedString(@"确定")block:^(QMUIDialogViewController *dialogViewController) {
                [weakself doSendWithType:@"1"];
            }];
            [dialogViewController show];
        }
        else
        {

        }
        
    } failure:^(NSString *error) {
        [HUDHelper alert:error];
    } hasCache:NO];
}

- (void)doSendWithType:(NSString *)type{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"invite_api" A:@"full_invite_code"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];

    [param setObject:dialogViewController.textField.text forKey:@"invite_code"];
    [param setObject:SafeStr(type) forKey:@"type"];

    [CYNET POSTv2:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [dialogViewController hide];
        [MBProgressHUD showTopTipMessage:ASLocalizedString(@"提交成功")];

    } failure:^(NSString *error) {
        [HUDHelper alert:error];
    } hasCache:NO];
}

#pragma mark - <QMUITextFieldDelegate>

- (BOOL)textFieldShouldReturn:(QMUITextField *)textField {

    return NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)segmentStyle1 {
//    list = @[ASLocalizedString(@"推荐"),
//             ASLocalizedString(@"在线"),
//             ASLocalizedString(@"魅力"),
//             ASLocalizedString(@"财气"),
////             ASLocalizedString(@"同城"),
//             ASLocalizedString(@"新人")//             ];
    
    list = @[ASLocalizedString(@"推荐"),
             ASLocalizedString(@"在线"),
             ];
//    list = @[ASLocalizedString(@"推荐"),
//             ASLocalizedString(@"新人"),
//             ASLocalizedString(@"在线"),
//             ];

    
    _segHead = [[MLMSegmentHead alloc] initWithFrame:CGRectMake(50, StatusBarHeight, SCREEN_WIDTH - 100, 40) titles:list headStyle:SegmentHeadStyleLine layoutStyle:_layout];
    //tab颜色
    _segHead.selectColor = MainColor;
    _segHead.deSelectColor = [UIColor blackColor];
    _segHead.lineColor = MainColor;
    _segHead.fontScale = 1;
    _segHead.lineHeight = 1.3;
    _segHead.fontSize = 15;
    _segHead.lineScale = .5;
    _segHead.headColor = CF6;
    _segHead.bottomLineHeight = 0;
    _segHead.deSelectColor = [UIColor colorWithRed:0.91 green:0.47 blue:0.62 alpha:1.00];
    self.view.backgroundColor = CF6;
    _segScroll = [[MLMSegmentScroll alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_segHead.frame), SCREEN_WIDTH, SCREEN_HEIGHT-CGRectGetMaxY(_segHead.frame)) vcOrViews:[self vcArr:list.count]];
    _segScroll.loadAll = NO;
    _segScroll.showIndex = 0;
    
    [MLMSegmentManager associateHead:_segHead withScroll:_segScroll completion:^{
        [self.view addSubview:_segHead];
        [self.view addSubview:_segScroll];
    }];
    
    UIButton *search = [[UIButton alloc] init];
    search.frame = CGRectMake(SCREEN_WIDTH - 50, StatusBarHeight - 5, 50, 50);
    search.imageEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
    [search setImage:[UIImage imageNamed:@"ic_search"] forState:UIControlStateNormal];
    [search addTarget:self action:@selector(handleSearchEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:search];
    
    UIButton *rank = [[UIButton alloc] init];
    rank.frame = CGRectMake(0, StatusBarHeight - 5, 50, 50);
    rank.imageEdgeInsets = UIEdgeInsetsMake(15, 15, 15, 15);
    [rank setImage:[UIImage imageNamed:@"ic_rank"] forState:UIControlStateNormal];
    [rank addTarget:self action:@selector(handleRankEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rank];
}

- (void)handleSearchEvent {
    HomeListSearchViewController *search = [[HomeListSearchViewController alloc] init];
//    [self.navigationController presentViewController:search animated:NO completion:nil];
    [self.navigationController pushViewController:search animated:YES];
}

- (void)handleRankEvent {
    OrderIndexViewController *order = [OrderIndexViewController new];
    [self.navigationController pushViewController:order animated:NO];
}

#pragma mark - 数据源
- (NSArray *)vcArr:(NSInteger)count {
    
    NSMutableArray *arr = [NSMutableArray array];

    
    
    //推荐
    HomeListViewController *vc = [HomeListViewController new];
    [arr addObject:vc];
    
    //新人
//    CYOrderViewController *order4 = [CYOrderViewController new];
//    order4.type = @"3";
//    [arr addObject:order4];
    
    //在线
    OnlineLogicViewController *hot = [OnlineLogicViewController new];
    [arr addObject:hot];
    hot.type = HomePageListTypeOnline;
    
    
    //关注
    //    OnlineLogicViewController *online = [OnlineLogicViewController new];
    //    online.type = HomePageListTypeFollow;
    //    [arr addObject:online];

//    //魅力
//    CYOrderViewController *order1 = [CYOrderViewController new];
//    order1.isHidenNaviBar = YES;
//    order1.type = @"1";
//    [arr addObject:order1];
//
//    //财气
//    CYOrderViewController *order2 = [CYOrderViewController new];
//    [arr addObject:order2];
//    order2.type = @"2";
    


    return arr;
}

-(void)viewWillAppear:(BOOL)animated
{
    self.isHidenNaviBar = YES;
    [super viewWillAppear:animated];
    //隐藏导航栏
    self.navigationController.navigationBar.hidden = YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
